import {
  Menu,
  Table,
  Button,
  Modal,
  message,
  ConfigProvider,
  Dropdown,
} from 'antd';
import { ExclamationCircleFilled } from '@ant-design/icons';
import type { ColumnsType, TableProps } from 'antd/es/table';
import { useState, useEffect, useImperativeHandle, useMemo, useLayoutEffect } from 'react';
import { useDebounceFunc } from '@inbiz/hooks';
import { getProcessList, delProcessList, getprocessStop } from '../servers';
import moment from 'moment';
import screenfull from 'screenfull';
import { useApp, useEvents } from '@inbiz/utils';
import api from '../api';
import VariateListModal from './VariateListModal';
import ModalSearchList from './ModalSearchList';
import ProcessDetailModal from './ProcessDetailModal';
import ProcessLogModal from '@components/business/process/ProcessCenter/preview/web/components/ProcessLogModal'
import { getLogInfo } from '@components/business/process/ProcessCenter/preview/web/utils';
import Check from '../assist/icons/check';
import { getMessage, TextWidget } from '@inbiz/react';
import { LoProps } from '../index';
import { getLangByActionType } from '../utils';
import { GlobalRegistry } from '@inbiz/core';
import { observer } from '@formily/react';
import { InbizIcon } from '@inbiz/utils';
import zhCN from 'antd/lib/locale/zh_CN';
import enUS from 'antd/es/locale/en_US';
import jaUS from 'antd/es/locale/ja_JP';
import Pagination from '@inbiz/basic/Pagination';

const { confirm } = Modal;
const TableList = observer((props: any) => {
  const { queryParams, ScopeProcess, processGroupSelector, state, inbiz, GetPage, expand } = props;
  const [formHeight, $formHeight] = useState(0);
  // 控制变量弹窗打开
  const [variateList, setVariateList] = useState(false);
  //控制流程详情弹窗打开
  const [ProcessDetail, setProcessDetail] = useState(false);
  //表格数据
  const [tableList, setTableList] = useState([]);
  //每页可显示多少条
  const [pageSize, setPageSize] = useState(GetPage);
  // 页码
  const [pageIndex, setPageIndex] = useState(1);
  //表格总页数
  const [tableListTotal, settableListTotal] = useState(0);
  //选中某行
  const [selected, setSelected] = useState<DataType[]>([]);
  //获取当前行IncidentID
  const [currentIncidentID, setCurrentIncidentID] = useState('');
  //获取某行数据
  const [activeRecord, setActiveRecord] = useState<any>();
  //控制查找当前审核人弹窗打开
  const [examine, setExamine] = useState(false);
  //加载中
  const [tableloading, setTableloading] = useState(false);
  //修改样式
  const [rowId, setRowId] = useState<any>(null);
  //是否全屏
  const [isFullscreen, setIsFullscreen] = useState(false);

  const [logVisible, $logVisible] = useState(false);
  const [logInfo, $logInfo] = useState(null);
  const [outParams, setOutParams] = useState({});
  //排序
  const [orderParams, setOrderParams] = useState({});
  const [taskId, setTaskId] = useState('');
  const [dropDownIndex, setDropDownIndex] = useState<any>(null);
  //多语言
  const common = getMessage('ProcessMonitoring.common');
  const strip = getMessage('ProcessMonitoring.strip');
  const [configEvents] = useEvents(props.callBackEvents, props.emit);
  const appInfo = useApp()

  useImperativeHandle(
    props.refs,
    () => ({
      ...api(configEvents, loadList),
    }),
    [],
  );

  //分页器多语言
  const getLang = useMemo(() => {
    const lang = GlobalRegistry.getDesignerLanguage();
    if (lang === 'zh-cn') return zhCN;
    if (lang === 'en-us') return enUS;
    if (lang === 'ja') return jaUS;
    return zhCN;
  }, [GlobalRegistry.getDesignerLanguage()]);

  // loadListData扩展方法
  const loadList = (e: LoProps) => {
    const { page, pageSize, ...params } = e;
    setOutParams(params);
    getTableData(page, pageSize, ScopeProcess, processGroupSelector, {
      ...queryParams,
      ...orderParams,
      ...params,
    });
  };

  //表格数据类型
  interface DataType {
    IncidentID: string;
    ProcessName: string;
    processGroupName: string;
    StratUserName: string;
    StartTime: number;
    EndTime: number;
    IncidentState: number;
    RuntimeState: number;
  }

  const onDropDownActionsClick = (e: any, row: any) => {
    switch (e?.key) {
      case '流程日志':
        getLogInfo(
          e?.domEvent,
          {
            processInstanceId: row.IncidentID,
            inItiateApplication: false,
            siteType: 3,
          },
          $logVisible,
          $logInfo,
        )
        break;
      case '变量':
        setActiveRecord(row);
        setVariateList(true);
        break;
      case '流程详情':
        setActiveRecord(row);
        setCurrentIncidentID(row.IncidentID);
        setProcessDetail(true);
        break;
      case '终止':
        termination(row);
        break;
      case '删除':
        handledelete(row);
        break;
      default:
        break;
    }
  };

  const dropDownActions = (_dropDownActions: any, row: any) => {
    const menu = (
      <Menu onClick={(e) => { onDropDownActionsClick(e, row) }}>
        {
          _dropDownActions?.map((item: string) => {
            if (item == '终止') {
              return (
                <Menu.Item key={item}>
                  <a
                    style={{
                      color: row?.IncidentState == 0 ? '' : '#bbbbbb',
                      cursor: row?.IncidentState == 0 ? 'pointer' : 'auto',
                    }}
                  >
                    <TextWidget>{getLangByActionType(item)}</TextWidget>
                  </a>
                </Menu.Item>
              )
            } else if (item == '删除') {
              return (
                <Menu.Item key={item}>
                  <a type="dashed">
                    <TextWidget>{getLangByActionType(item)}</TextWidget>
                  </a>
                </Menu.Item>
              )
            } else {
              return (
                <Menu.Item key={item}>
                  <a>
                    <TextWidget>{getLangByActionType(item)}</TextWidget>
                  </a>
                </Menu.Item>
              )
            }
          })
        }
      </Menu>
    );
    return <Dropdown.Button overlay={menu} />
  }

  const actionsColumn = () => {
    const _dropDownActions = (dropDownIndex || dropDownIndex == 0) ? [...props.InlineOperation].slice(dropDownIndex) : [];
    let showMore = !!dropDownIndex;
    return ({
      title: getMessage('ProcessMonitoring.operation'), //操作
      key: 'handle',
      className: 'headcolor process-monitoring-action-column',
      width: 250,
      render: (_, record) => (
        <div style={{ height: 22, overflow: 'hidden' }}>
          <div className='process-monitoring-action-column-inner'>
            {props.InlineOperation.includes('流程日志') && (
              <a
                onClick={
                  (e) => {
                    getLogInfo(
                      e,
                      {
                        processInstanceId: record.IncidentID,
                        inItiateApplication: false,
                        siteType: 3,
                      },
                      $logVisible,
                      $logInfo,
                    )
                  }
                }
              >
                {/* 流程日志 */}
                <TextWidget>ProcessMonitoring.processLog</TextWidget>
              </a>
            )}
            {props.InlineOperation.includes('变量') && (
              <a
                onClick={() => {
                  setActiveRecord(record);
                  setVariateList(true);
                }}
              >
                {/* 变量 */}
                <TextWidget>ProcessMonitoring.variable</TextWidget>
              </a>
            )}
            {props.InlineOperation.includes('流程详情') && (
              <a
                onClick={() => {
                  setActiveRecord(record);
                  setCurrentIncidentID(record.IncidentID);
                  setProcessDetail(true);
                }}
              >
                {/* 流程详情 */}
                <TextWidget>ProcessMonitoring.processDetails</TextWidget>
              </a>
            )}
            {props.InlineOperation.includes('终止') && (
              <a
                onClick={() => {
                  termination(record);
                }}
                style={{
                  color: record?.IncidentState == 0 ? '' : '#bbbbbb',
                  cursor: record?.IncidentState == 0 ? 'pointer' : 'auto',
                }}
              >
                {/* 终止 */}
                <TextWidget>ProcessMonitoring.termination</TextWidget>
              </a>
            )}
            {props.InlineOperation.includes('删除') && (
              <a
                onClick={() => {
                  handledelete(record);
                }}
                type="dashed"
              >
                {/* 删除 */}
                <TextWidget>ProcessMonitoring.delete</TextWidget>
              </a>
            )}
            {
              showMore
              &&
              dropDownActions(_dropDownActions, record)
            }
          </div>
        </div>
      ),
    })
  };

  //表格列
  const columnsTable: ColumnsType<DataType> = [
    {
      dataIndex: 'IncidentID',
      key: 'IncidentID',
      title: getMessage('ProcessMonitoring.processNo'), //流程编号
      className: 'headcolor',
      ellipsis: true,
      render: (text) => <span>{text}</span>,
    },
    {
      title: getMessage('ProcessMonitoring.processName'), //流程名称
      dataIndex: 'ProcessName',
      key: 'ProcessName',
      ellipsis: true,
      render: (text) => <span>{text}</span>,
      className: 'headcolor',
    },
    {
      title: getMessage('ProcessMonitoring.sponsor'), //发起人
      dataIndex: 'StratUserName',
      key: 'StratUserName',
      ellipsis: true,
      render: (text) => <span>{text}</span>,
      className: 'headcolor',
    },
    {
      title: getMessage('ProcessMonitoring.originatingTime'), //发起时间
      dataIndex: 'StartTime',
      key: 'StartTime',
      className: 'headcolor',
      ellipsis: true,
      render: (t, r, i) => {
        if (t) {
          return moment(t).format('YYYY-MM-DD HH:mm:ss');
        } else {
          return '';
        }
      },
      sorter: true,
    },
    {
      title: getMessage('ProcessMonitoring.completionTime'), //完成时间
      dataIndex: 'EndTime',
      key: 'EndTime',
      ellipsis: true,
      className: 'headcolor',
      render: (t, r, i) => {
        if (t) {
          return moment(t).format('YYYY-MM-DD HH:mm:ss');
        } else {
          return '';
        }
      },
      sorter: true,
    },
    {
      title: getMessage('ProcessMonitoring.processStatus'), //流程状态
      dataIndex: 'IncidentState',
      key: 'IncidentState',
      className: 'headcolor',
      ellipsis: true,
      render: (r) => {
        switch (r) {
          case 0:
            return getMessage('ProcessMonitoring.underApproval'); //审批中
          case 1:
            return getMessage('ProcessMonitoring.approvalCompleted'); //审批完成
          case 2:
            return getMessage('ProcessMonitoring.termination'); //终止
        }
      },
    },
    {
      title: getMessage('ProcessMonitoring.RuntimeState'), //运行状态
      dataIndex: 'RuntimeState',
      key: 'RuntimeState',
      className: 'headcolor',
      ellipsis: true,
      render: (r) => {
        if (r === 1) {
          return getMessage('ProcessMonitoring.normal'); //正常
        } else if (r === 0) {
          return getMessage('ProcessMonitoring.abnormal'); //异常
        }
      },
    },
  ];
  if (props.processGroup !== false) {
    columnsTable.splice(2, 0, {
      title: getMessage('ProcessMonitoring.processGroup'), //流程分组
      dataIndex: 'processGroupName',
      key: 'processGroupName',
      ellipsis: true,
      render: (text) => <span>{text}</span>,
      className: 'headcolor',
    });
  };
  if (props.exposureConfig?.ownership) {
    columnsTable.push({
      title: getMessage('ProcessMonitoring.source'), //来源
      key: 'source',
      dataIndex: 'source',
      className: 'headcolor',
      ellipsis: true,
    });
  };
  columnsTable.push(actionsColumn());

  useEffect(() => {
    const _actionColumn = document.getElementsByClassName('process-monitoring-action-column')?.[1];
    if (_actionColumn) {
      const action = _actionColumn.getElementsByClassName('process-monitoring-action-column-inner')?.[0];
      const actions = action.getElementsByTagName('a');
      let _change = false;
      if (actions && actions?.length > 0) {
        for (let i = 0; i < actions.length; i++) {
          if (i > 0 && actions[i].offsetLeft <= actions[i - 1].offsetLeft) {
            setDropDownIndex(i);
            _change = true;
            break;
          };
        };
      };
      if(_change === false){
        setDropDownIndex(null);
      };
    };
  }, [document.getElementsByClassName('process-monitoring-action-column'), tableList, GlobalRegistry.getDesignerLanguage(), props]);

  //调用表格数据
  const getTableData = useDebounceFunc((
    pageIndex: number,
    pageSize: number,
    ScopeProcess: string,
    processGroupSelector: any,
    otherparams?: any,
  ) => {
    setTableloading(true);
    let params = {
      pageIndex,
      pageSize,
      ...otherparams,
      state: state,
    };
    // 当前应用
    if (ScopeProcess == 'currentApplication') {
      params['appId'] = appInfo.AppId;
    }
    // 分组
    if (ScopeProcess == 'group') {
      params['groupId'] = processGroupSelector
        ?.map((item: { groupId: any }) => item?.groupId)
        ?.join('/');
    }
    getProcessList(params)
      .then((res: any) => {
        let result = res?.details?.rows;
        let result1 = res?.details?.total;
        if (res?.code == 200 && res?.details) {
          setTableList(result);
          settableListTotal(result1);
        } else {
          setTableList([]);
          settableListTotal(0);
        }
        setTableloading(false);
      })
      .catch((err: any) => {
        setTableList([]);
        settableListTotal(0);
        setTableloading(false);
      });
  });

  useLayoutEffect(() => {
    const domFormFormat: any = document.querySelector('.header-form');
    if (domFormFormat) {
      $formHeight(domFormFormat?.offsetHeight || 0);
    }
  }, [expand])

  //分页排序
  useEffect(() => {
    getTableData(pageIndex, pageSize, ScopeProcess, processGroupSelector, {
      ...queryParams,
      ...orderParams,
      ...outParams,
    });
  }, [
    pageIndex,
    pageSize,
    ScopeProcess,
    processGroupSelector,
    orderParams,
    queryParams,
  ]);

  useEffect(() => {
    setPageSize(GetPage);
  }, [GetPage]);

  //查询
  useEffect(() => {
    setPageIndex(1);
  }, [queryParams]);

  //排序
  const onChange: TableProps<DataType>['onChange'] = (
    pagination,
    filters,
    sorter: any,
  ) => {
    if (sorter?.field && sorter?.order) {
      setOrderParams({
        orderName: sorter?.field,
        orderType: sorter?.order == 'ascend' ? 'asc' : 'desc',
      });
    }
    if (sorter?.field && !sorter?.order) {
      setOrderParams({});
    }
  };

  //查看当前审核人弹窗
  const search = () => {
    if (selected && selected?.length) {
      setExamine(true);
    } else {
      message.info(getMessage('ProcessMonitoring.PleaseSelectTheRoeToView'));
    }
  };

  // 确认删除的弹窗
  const handledelete = (record: any) => {
    confirm({
      title: getMessage(
        'ProcessMonitoring.AreYouSureYouWantToDeleteThisProcess',
      ), //确定要删除此流程
      icon: <ExclamationCircleFilled />,
      okText: getMessage('ProcessMonitoring.determine'), //确定
      cancelText: getMessage('ProcessMonitoring.cancel'), //取消
      onOk() {
        DelList(record);
      },
      onCancel() { },
    });
  };

  //删除方法
  const DelList = (record: any) => {
    //调用删除接口
    if (record?.IncidentID) {
      delProcessList(record?.IncidentID).then((res: any) => {
        if (res?.code == '200') {
          message.success(getMessage('ProcessMonitoring.deletionSucceeded')), //删除成功
            getTableData(
              pageIndex,
              pageSize,
              ScopeProcess,
              processGroupSelector,
              {
                ...queryParams,
                ...orderParams,
                ...outParams,
              },
            );
        } else {
          message.error(getMessage('ProcessMonitoring.deleteFailed')); //删除失败
        }
      });
    }
  };

  //终止
  const termination = (record: any) => {
    if (record.IncidentState == 0) {
      confirm({
        title: getMessage('ProcessMonitoring.ConfirmToTerminateTheProcess'), //确认要终止流程？
        icon: <ExclamationCircleFilled />,
        okText: getMessage('ProcessMonitoring.determine'), //确定
        cancelText: getMessage('ProcessMonitoring.cancel'), //取消
        onOk() {
          getprocessStop({
            processInstanceId: record.IncidentID,
            taskId: taskId,
          }).then((res: any) => {
            if (res?.code == '200') {
              message.success(
                getMessage('ProcessMonitoring.terminatedSuccessfully'),
              ), //终止成功
                getTableData(
                  pageIndex,
                  pageSize,
                  ScopeProcess,
                  processGroupSelector,
                  {
                    ...queryParams,
                    ...orderParams,
                    ...outParams,
                  },
                );
            } else {
              message.error(getMessage('ProcessMonitoring.terminationFailed')); //终止失败
            }
          });
        },
      });
    } else {
      return;
    }
  };

  //修改被选中表格样式
  const setRowClassName = (record: any) => {
    return record.IncidentID === rowId ? 'clickRowStyle' : '';
  };

  //放大与缩小
  const getFullScreenElement = () => {
    let managerModal = document.getElementsByClassName(
      'process-detail-modal-wrapper',
    )[0];
    let fullScreenElement =
      managerModal?.getElementsByClassName('ant-modal-content')[0];
    return fullScreenElement;
  };
  const fullScreenHandleClick = () => {
    if (!screenfull.isEnabled) {
      message.warning(getMessage('version.cantFullScreen'));
      return false;
    }
    screenfull.toggle(getFullScreenElement());
    setIsFullscreen(!isFullscreen);
    return;
  };

  return (
    <ConfigProvider locale={getLang}>
      {/* {查找当前审核人按钮} */}
      <div className="table-top">
        {props.ToolbarOperation.includes('查看当前审核人') && (
          <Button onClick={search} icon={<Check />}>
            <TextWidget>ProcessMonitoring.ViewCurrentApprover</TextWidget>
          </Button>
        )}
      </div>
      {/* {表格主体} */}
      <div className="table-list">
        <div className="table-wrapper">
          <Table
            onChange={onChange}
            size="small"
            bordered={true}
            pagination={false}
            columns={columnsTable}
            dataSource={tableList}
            loading={tableloading}
            scroll={{ y: `calc(100vh - ${(props.ToolbarOperation.includes('查看当前审核人') ? 270 : 235) + formHeight}px)` }}
            rowClassName={setRowClassName}
            onRow={(record: any) => {
              return {
                onClick: (event) => {
                  // 点击行
                  setSelected([record]);
                  setRowId(record.IncidentID);
                },
              };
            }}
          />
        </div>
        <div className="table-pagination">
          {/* {分页器} */}
          <Pagination
            refreshData={() => {
              getTableData(
                pageIndex,
                pageSize,
                ScopeProcess,
                processGroupSelector,
                {
                  ...queryParams,
                  ...orderParams,
                  ...outParams,
                },
              );
            }}
            pageRefresh={true}
            pagination={{
              current: pageIndex,
              pageSize: pageSize,
              total: tableListTotal,
              showQuickJumper: true,
              showSizeChanger: true,
              pageSizeOptions: [10, 20, 30, 50, 100],
              showLessItems: true,
              // @ts-ignore
              showTotal: true
            }}
            onPageChange={({ current, pageSize }) => {
              setPageIndex(current);
              setPageSize(pageSize);
            }}
          />
        </div>

        {/* 流程日志弹窗组件 */}
        <ProcessLogModal
          visible={logVisible}
          $visible={$logVisible}
          logInfo={logInfo}
        />

        {/* 变量列表弹窗组件*/}
        <Modal
          className="VariateListModal"
          bodyStyle={{ width: 450, height: 250 }}
          width="450"
          title={getMessage('ProcessMonitoring.variableList')}
          visible={variateList}
          centered={true}
          footer={null}
          destroyOnClose={true}
          onOk={() => {
            setVariateList(false);
          }}
          onCancel={() => {
            setVariateList(false);
            setActiveRecord(null);
          }}
        >
          <VariateListModal activeRecord={activeRecord} />
        </Modal>

        {/* 流程详情弹窗组件 */}
        <Modal
          className="ProcessDetailModal"
          bodyStyle={{
            height: 'calc(100% - 40px)',
          }}
          width={'1000px'}
          title={getMessage('ProcessMonitoring.processDetails')}
          visible={ProcessDetail}
          centered={true}
          footer={null}
          destroyOnClose={true}
          wrapClassName="process-detail-modal-wrapper"
          onOk={() => {
            setProcessDetail(false);
            setCurrentIncidentID('');
            setActiveRecord(null);
          }}
          onCancel={() => {
            setProcessDetail(false);
            setCurrentIncidentID('');
            setActiveRecord(null);
          }}
        >
          <>
            <div className="process-detail-modal-wrapper-icon">
              <InbizIcon
                onClick={fullScreenHandleClick}
                type={isFullscreen ? 'icon-huanyuan' : 'icon-ic-zuidahua'}
                style={{ fontSize: 22, marginRight: 20 }}
              />
            </div>
            <ProcessDetailModal
              currentIncidentID={currentIncidentID}
              activeRecord={activeRecord}
            />
          </>
        </Modal>

        {/* {查找当前审核人弹窗组件} */}
        <Modal
          className="ModalSearchList"
          bodyStyle={{ width: 450, height: 300 }}
          width="450"
          title={getMessage('ProcessMonitoring.ViewCurrentApprover')}
          visible={examine}
          centered={true}
          destroyOnClose={true}
          onOk={() => setExamine(false)}
          onCancel={() => setExamine(false)}
          footer={null}
        >
          <ModalSearchList
            currentIncidentID={selected[0]?.IncidentID}
            setExamine={setExamine}
          />
        </Modal>
      </div>
    </ConfigProvider>
  );
});

export default TableList;
